<template>
  <div class="home">
    <header class="header">
      <!-- 搜索栏 -->
      <div class="top-bar">
        <div class="search-wrapper">
          <div class="icon-wrapper">
            <i class="iconfont icon-Search"></i>
          </div>
          <div class="input">
            <input type="text" placeholder="搜索图纸编号" @keyup.enter="searchDrawing()" v-model="iptVal" />
          </div>
          <div class="iconfont-wrapper" v-if="showDelete" @click="deleteVal()">
            <i class="iconfont icon-shanchu"></i>
          </div>
        </div>
      </div>
      <!-- 焦点图 -->
      <div class="banner">
        <van-swipe
          :autoplay="3000"
          indicator-color="#1989fa"
          :show-indicators="true"
          style="height:100%"
        >
          <van-swipe-item
            style="width:100%;height:100%"
            v-for="item in imgList"
            :key="item.BannerDes"
          >
            <img
              class="banner-img"
              v-lazy="showImg(item.BannerImg || '')"
              style="width:3.45rem;height:0.97rem"
            />
          </van-swipe-item>
        </van-swipe>
      </div>
    </header>
    <!-- 下拉导航 -->
    <nav class="select-nav">
      <div
        class="item"
        @click="showPopupFn(item.text)"
        v-for="(item,index) in selectNavList"
        :key="index"
      >
        <div class="icon-wrapper">
          <i class="iconfont icon-fenggepitchon" :class="item.icon"></i>
        </div>
        <div class="text">{{item.text}}</div>
      </div>
    </nav>
    <!-- 图纸列表 -->
    <main ref="wrapper">
      <!-- 通过vant的组件实现下拉刷新上拉加载（没有使用better-scroll插件） -->
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh" class="pull-refresh">
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          class="content-wrapper"
          :offset="20"
          ref="list"
        >
          <div class="drawing-item-wrapper" v-for="(item,index) in drawingList" :key="index">
            <div class="drawing-item" @click="toDetailPage(index)">
              <div class="img-wrapper">
                <img v-lazy="showImgwrapper(item.Renderings || '')" alt />
              </div>
              <div class="info">
                <div class="title">图纸编号：{{item.BuildingName}}</div>
                <div class="des">占地面积：{{item.FloorSpace}}m²</div>
                <div class="des">建筑面积：{{item.BuildUpArea}}m²</div>
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
      <!-- </div> -->
    </main>
    <!-- 弹出层 -->
    <van-popup
      v-model="showPopup"
      class="popup"
      position="top"
      :style="{ height: '30%' }"
      @close="closePopupFn()"
    >
      <div class="filter-wrapper">
        <SelectTag
          title="风格"
          :showPopup="showfengge"
          :Tag="resStyTag"
          subItem="StyleName"
          :activeItem="activeItem"
          @btnFn="btnFn"
        />
        <SelectTag
          title="面积"
          :showPopup="showmianji"
          :Tag="resBuildAreaData"
          subItem="text"
          :activeItem="activeItem"
          @btnFn="btnFn"
        />
        <SelectTag
          title="特征"
          :showPopup="showtezheng"
          :Tag="resFeaTag"
          subItem="FeatureName"
          :activeItem="activeItem"
          @btnFn="btnFn"
        />
        <SelectTagFiltrate
          :title="filtrateTitle"
          :showPopup="showshaixuan"
          :Tag="resFiltrate"
          subItem="text"
          :activeFiltrate="activeFiltrate"
          @btnFiltrateFn="btnFiltrateFn"
        />
      </div>
    </van-popup>
  </div>
</template>

<script>
// @ is an alias to /src
import {
  baseURL,
  getImg,
  getAllDrawing,
  getBanner,
  searchDrawing,
  getStyleTag,
  getFeatureTag
} from '@/api/config'
// 获取面积和筛选的标签
import {
  buildAreaData,
  floorNumData,
  widthData,
  depthData
} from '@/assets/data.js'
// 导入组件
import SelectTag from '@/components/base/select-tag'
import SelectTagFiltrate from '@/components/base/select-tag-filtrate'

export default {
  name: 'home',
  components: {
    SelectTag,
    SelectTagFiltrate
  },
  watch: {
    // 输入框为空时(非长度为零)拿取全部数据
    iptVal: function (val, oldVal) {
      if (val === '') this.getDrawingList()
    }
  },
  data () {
    return {
      selectNavList: [
        {
          text: '风格',
          icon: 'icon-fenggepitchon'
        },
        {
          text: '面积',
          icon: 'icon-mianji-xian'
        },
        {
          text: '特征',
          icon: 'icon-jurassic_shuxing'
        },
        {
          text: '筛选',
          icon: 'icon-shaixuan'
        }
      ],
      // 无限滚动
      loading: false,
      finished: false,
      isLoading: false,
      // 请求数据的长度
      TotalCount: '',
      TotalPage: '',
      // 输入框
      iptVal: '',
      currentPage: 1,
      // banner图片和图纸数据
      imgList: [],
      drawingList: [],
      // 后台获取的标签及数据
      resStyTag: [],
      resFeaTag: [],
      resBuildAreaData: [],
      resFiltrate: [],
      // 筛选的三个标题
      filtrateTitle: [],
      // 控制弹框的显示 以及需要关闭的弹框
      showPopup: false,
      showfengge: false,
      showmianji: false,
      showtezheng: false,
      showshaixuan: false,
      closePopup: '',
      // 选中的标签项
      activeItem: '',
      activeFiltrate: ['', '', '']
    }
  },
  computed: {
    showDelete () {
      if (this.iptVal === '') return false
      return true
    },
    showImgwrapper (imgURI) {
      return (img) => {
        return baseURL + getImg + img.replace(/\\/g, imgURI)
      }
    },
    // 处理图片
    showImg () {
      return (img) => {
        return baseURL + getImg + img.replace(/\\/g, encodeURIComponent('$$'))
        //
      }
    }
  },
  created () {
    this.getBanner()
    this.getTag()
    this.getLeftoverTag()
    this.getDrawingList()
  },
  methods: {
    // 异步更新数据
    onLoad () {
      setTimeout(() => {
        this.currentPage++
        this.getDrawingList({
          currentPage: this.currentPage
        }, 500)
        // 加载状态结束
        if (this.currentPage >= this.TotalPage) {
          // 数据全部加载完成
          this.finished = true
        }
      }, 500)
    },
    // 刷新
    onRefresh () {
      setTimeout(() => {
        this.$toast('刷新成功')
        this.isLoading = false
        this.currentPage = 1
        this.finished = false
        this.drawingList = []
        this.getDrawingList({
          currentPage: this.currentPage
        })
      }, 500)
    },
    // 显示弹框并且给filterTagData需要过滤的数据
    showPopupFn (val) {
      this.showPopup = true
      switch (val) {
        case '风格':
          this.showfengge = true
          this.closePopup = 'showfengge'
          break
        case '面积':
          this.showmianji = true
          this.closePopup = 'showmianji'
          break
        case '特征':
          this.showtezheng = true
          this.closePopup = 'showtezheng'
          break
        case '筛选':
          this.showshaixuan = true
          this.closePopup = 'showshaixuan'
          break
      }
    },
    // 去往详情页
    toDetailPage (index) {
      // 记录详情页图纸所在的索引
      this.$store.commit('setDetailIndex', [index])
      this.$router.push({
        name: `drawingDetail`
      })
    },
    // 清空输入框
    deleteVal () {
      this.iptVal = ''
      this.getDrawingList()
    },
    // 获取搜索的图纸数据
    async searchDrawing () {
      var val = this.iptVal || ''
      let res = await this.get(searchDrawing + encodeURI(val))
      if (res.data.length === 0) {
        this.drawingList = []
        return this.$toast('无法搜索到图纸数据')
      }
      this.drawingList = res.data
    },
    // 获取全部图纸 /* 参数过多的话可以写这种形式 */
    async getDrawingList (obj = {}) {
      this.loading = true
      // 初始化传入的参数
      var areaCode = obj['areaCode'] || 0 // 区域
      var buildPrice = obj['buildPrice'] || 0 // 造价
      var style = obj['style'] || 0 // 风格
      var buildArea = obj['buildArea'] || 0 // 面积
      var feature = obj['feature'] || 0 // 特征
      var floorNum = obj['floorNum'] || 0 // 层数
      var width = obj['width'] || 0 // 面宽
      var depth = obj['depth'] || 0 // 进深
      var currentPage = obj['currentPage'] || 1 // 当前页码
      var pageNum = 10 // 请求条数
      let res = await this.get(
        `${getAllDrawing}${areaCode}_${style}_${buildArea}_${floorNum}_${feature}_${buildPrice}_${width}_${depth}/${currentPage}/${pageNum}`
      )
      if (res.status !== 200) return this.$toast('无法获取到图纸数据')
      if (res.data.Data.length === 0) {
        this.$toast('暂无图纸数据')
      } else {
        this.$toast('加载完成')
        this.loading = false
      }
      let { Data, CurrentPage, TotalCount, TotalPage } = res.data
      // 数据条数
      this.TotalCount = TotalCount
      this.TotalPage = TotalPage
      // 判断是不是筛选
      if (obj.filtrate === true) {
        this.drawingList = Data
      } else {
        this.drawingList = this.drawingList.concat(Data)
      }
      this.resLength = Data.length
      this.currentPage = CurrentPage
      // 存储图纸数据
      this.$store.commit('setdrawingList', [this.drawingList])
    },
    // 获取banner图片
    async getBanner () {
      let res = await this.get(getBanner)
      if (res.status !== 200) return this.$toast('获取banner数据失败')
      this.imgList = res.data
    },
    // 获取弹框的标签
    async getTag () {
      let resSty = await this.get(getStyleTag)
      if (resSty.status !== 200) {
        this.$toast('无法获取到风格标签')
      } else {
        resSty.data.unshift({
          ID: 0,
          StyleName: '全部'
        })
        this.resStyTag = resSty.data
      }
      let resFea = await this.get(getFeatureTag)
      if (resFea.status !== 200) {
        this.$toast('无法获取到特征标签')
      } else {
        resFea.data.unshift({
          ID: 0,
          FeatureName: '全部'
        })
        this.resFeaTag = resFea.data
      }
    },
    // 获取筛选弹框的标签
    getLeftoverTag () {
      this.resBuildAreaData = buildAreaData
      this.filtrateTitle = ['层数', '面宽', '进深']
      this.resFiltrate = [floorNumData, widthData, depthData]
    },
    // 标签选中事件
    selectedTag (val) {
      this.activeItem = val
    },
    btnFn (propsVal) {
      var selectVal = propsVal[0]
      var id = propsVal[1]
      if (selectVal) this.activeItem = selectVal
      if (this.activeItem === '') {
        return this.$toast('请选择标签')
      }
      switch (this.closePopup) {
        case 'showfengge':
          this.getDrawingList({ style: id, filtrate: true })
          break
        case 'showmianji':
          this.getDrawingList({ buildArea: id, filtrate: true })
          break
        case 'showtezheng':
          this.getDrawingList({ feature: id, filtrate: true })
          break
      }
      // 关闭外层的弹框，关闭指定的弹框子项
      this.showPopup = false
      this[this.closePopup] = false
    },
    btnFiltrateFn (propsVal) {
      var selectVal = propsVal[0]
      var selectId = propsVal[1]
      // 筛选弹框
      var flag = selectVal.some((item) => {
        return item !== ''
      })
      if (!flag) return this.$toast('请选择标签')
      // 发请求
      this.getDrawingList({
        floorNum: selectId[0],
        width: selectId[1],
        depth: selectId[2],
        filtrate: true
      })
      this.activeFiltrate = selectVal
      this.showPopup = false
      this[this.closePopup] = false
    },
    closePopupFn () {
      this.showPopup = false
      this[this.closePopup] = false
    }
  }
}
</script>

<style lang="stylus" >
.home
  height 100%
  .header
    background-image linear-gradient(0deg, #fff 30%, #1da7e8 70%)
    .top-bar
      padding 0.14rem 0.15rem
      .search-wrapper
        display flex
        align-items center
        border-radius 0.08rem
        background-color #fff
        overflow hidden
        .icon-wrapper
          display flex
          padding 0 0.13rem
          .iconfont
            color #cbcbcb
            font-size 0.13rem
        .input
          display flex
          flex 1
          height 0.35rem
          padding 0 0.04rem
          letter-spacing 0.01rem
          input
            flex 1
            outline 0
            border none
            &::placeholder
              color #333
              font-size 0.13rem
        .iconfont-wrapper
          .iconfont
            color #cbcbcb
            font-size 0.13rem
            padding 0 0.08rem
    .banner
      width 3.45rem
      height 0.97rem
      margin 0 auto
      margin-top 0.1rem
      border-radius 0.1rem
      overflow hidden
  .select-nav
    display flex
    align-items center
    padding 0.25rem 0.13rem 0 0.13rem
    .item
      display flex
      align-items center
      flex-direction column
      flex 1
      .icon-wrapper
        .icon-fenggepitchon
          font-size 0.26rem
          color #398eca
        .icon-mianji-xian
          font-size 0.26rem
          color #398eca
        .icon-jurassic_shuxing
          font-size 0.26rem
          color #398eca
        .icon-shaixuan
          font-size 0.26rem
          color #398eca
      .text
        margin-top 0.07rem
        line-height 0.13rem
        color #333
        font-size 0.13rem
        font-weight 700
        letter-spacing 0.02rem
  main
    position absolute
    top 2.6rem
    bottom 0
    left 0
    right 0
    overflow scroll
    &::-webkit-scrollbar
      display none
    .pull-refresh
      .content-wrapper
        .drawing-item-wrapper
          display inline-block
          width 50%
          padding 0.05rem 0
          .drawing-item
            width 1.67rem
            margin 0 auto
            box-shadow 0rem 0.01rem 0.03rem 0rem rgba(96, 120, 234, 0.1)
            border-radius 0.1rem
            overflow hidden
            .img-wrapper
              img
                width 100%
                height 1.07rem
            .info
              padding 0.07rem 0.05rem
              .title
                color #333
                font-size 0.12rem
                font-weight 700
                line-height 0.18rem
                letter-spacing 0.01rem
                text-overflow ellipsis
                overflow hidden
                white-space nowrap
              .des
                color #f5640c
                font-size 0.09rem
                font-weight 700
                line-height 0.18rem
                letter-spacing 0.01rem
                text-overflow ellipsis
                overflow hidden
                white-space nowrap
  .popup
    .filter-wrapper
      .filter-option
        padding 0.06rem 0.18rem
        .title
          padding 0 0 0.08rem 0
          color #333
          line-height 0.13rem
          font-weight 700
          text-align center
        .select-tag
          display flex
          flex-wrap wrap
          .item-wrapper
            width 25%
            padding 0.05rem 0
            .item
              margin 0 auto
              width 0.75rem
              height 0.25rem
              line-height 0.25rem
              border solid 0.01rem #ccc
              color #999
              font-size 0.11rem
              text-align center
              border-radius 0.02rem
          .active
            .item
              background-color #bbe4f8
              border solid 0.01rem #1da7e8
              color #1da7e8
      .btn-wrapper
        padding 0.16rem
        .btn
          display flex
          align-items center
          justify-content center
          margin 0 auto
          width 2.2rem
          line-height 0.39rem
          color #fff
          font-size 0.14rem
          font-weight 700
          background-color #1da7e8
          border-radius 0.05rem
          text-align center
</style>
